;*******************************************************************************
; Name: start.asm
; Copyright: Kieran Foot 2009
; Author: Kieran Foot
; Date: 12/06/09 12:35
; Description: MGOS Startup file
;*******************************************************************************

;------------------------------;
; Multiboot header definitions ;
;------------------------------;
MODULEALIGN equ  1<<0                   ; align loaded modules on page boundaries
MEMINFO     equ  1<<1                   ; provide memory map
FLAGS       equ  MODULEALIGN | MEMINFO  ; this is the Multiboot 'flag' field
MAGIC       equ    0x1BADB002           ; 'magic number' lets bootloader find the header
CHECKSUM    equ -(MAGIC + FLAGS)        ; checksum required

;---------------------;
; Start of the loader ;
;---------------------;
[SECTION .text]
align 4

[GLOBAL loader]
loader:

	;------------------;
	; Multiboot header ;
	;------------------;
	MultiBootHeader:
		dd MAGIC
		dd FLAGS
		dd CHECKSUM
		
	;----------------------;
	; Define the stacksize ;
	;----------------------;
	STACKSIZE equ 0x4000
	
	;-----------------;
	; Setup the stack ;
	;-----------------;
	mov esp, stack+STACKSIZE
	
	;-----------------------;
	; Save multiboot values ;
	;-----------------------;
	push eax
	push ebx

	;--------------------------;
	; Call global CONSTRUCTORS ;
	;--------------------------;
	[EXTERN start_ctors]
	[EXTERN end_ctors]
	
	static_ctors_loop:
   		mov ebx, start_ctors
   		jmp .test
	.body:
   		call [ebx]
   		add ebx,4
	.test:
   		cmp ebx, end_ctors
   		jb .body

	;---------------------------;
	; Call kernel main function ;
	;---------------------------;
	[EXTERN main]
	call main

	;-------------------------;
	; Call global DESTRUCTORS ;
	;-------------------------;
	[EXTERN start_dtors]
	[EXTERN end_dtors]
	
	static_dtors_loop:
   		mov ebx, start_dtors
   		jmp .test
	.body:
   		call [ebx]
   		add ebx,4
	.test:
   		cmp ebx, end_dtors
   		jb .body

	
	;---------------------------------------------------------;
	; Kernel finished running, stop interrupts & halt the CPU ;
	;---------------------------------------------------------;
	cli
	hlt

	;---------------------------------------------------------------;	
	; If we reach here the HLT didn't work, loop forever trying HLT ;
	;---------------------------------------------------------------;
	hang:
		hlt
		jmp hang
		
[SECTION .bss]
align 32

	;------------------;
	; Define the stack ;
	;------------------;
	stack:
		resb STACKSIZE
